import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {

    }
    //水果成篮
    public int totalFruit(int[] fruits) {
        int n = fruits.length;
        int[] hash = new int[n];//记录滑动窗口
        int count = 0;//滑动窗口中水果的种类数量
        int left = 0;
        int right = 0;
        int ret = 0;
        while(right<n){
            //进窗口
            if(hash[right]==0&&count<2){
                count++;
                hash[right]++;
                right++;
            }
            if(right<n&&hash[right]>0){
                right++;
            }
            if(right==n||right<n&&hash[right]==0&&count==2){
                //更新结果
                ret = Math.max(right-left,ret);
                //出窗口
                while(hash[left]==0){
                    hash[left]--;
                    left++;
                }
                count--;
            }
        }
        return ret;
    }
    //水果成篮
    public int totalFruit2(int[] fruits){
        int n = fruits.length;
        int ret = 0;
        Map<Integer,Integer> map = new HashMap<>();//统计窗口的水果
        for(int left = 0, right = 0;right < n ;right++){
            //进窗口
            int in = fruits[right];
            map.put(in,map.getOrDefault(in,0)+1);
            //出窗口
            while(map.size()>2){
                int out = fruits[left];
                map.put(out,map.get(out)-1);
                if(map.get(out)==0){
                    map.remove(out);
                }
                left++;
            }
            //更新结果
            ret = Math.max(ret,right - left+1);
        }
        return ret;
    }
}
